package DAO;

import Damain.emp;
import Utils.JdbcUtils;

import java.security.PrivateKey;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class EmpDaoImpl implements EmpDao {

    @Override
    public int selCount() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        int count = 0;

        //创建链接
        connection = JdbcUtils.getConnection();
        String sql = "select count(*) from t_emp";
        try {
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                count = resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection, statement, resultSet);
        }
        return count;
    }

    /**
     * 查询表数据
     */
    @Override
    public List<emp> selPage(int pageCode, int pageSize) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<emp> list = new ArrayList<>();
        connection = JdbcUtils.getConnection();
        //复合查询语句  第一个占位符表示从那一条数据开始,查询每页条数据
        String sql = "SELECT *FROM t_emp ORDER BY edate limit ?,?";
        try {
            statement = connection.prepareStatement(sql);
            //算法为当前页-1*每页显示的条数
            statement.setInt(1, (pageCode - 1) * pageSize);
            statement.setInt(2, pageSize);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                //封装数据
                emp emp = new emp();
                emp.setId(resultSet.getInt("id"));
                emp.setEname(resultSet.getString("ename"));
                emp.setAge(resultSet.getInt("age"));
                emp.setSex(resultSet.getString("sex"));
                emp.setSal(resultSet.getInt("sal"));
                emp.setBirthday(resultSet.getString("birthday"));
                emp.setEdate(resultSet.getString("edate"));
                list.add(emp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection, statement, resultSet);
        }
        return list;


    }
}
